<?php

namespace App\Http\Controllers\Steward;

use App\Models\Bill\Bill;
use App\Models\Bill\BillGoods;
use App\Models\Bill\BillPrintLog;
use App\Models\ConfigureFunction;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;
use App\Models\Mall\MallMaster;
use App\Models\Mall\MallUser;


class ClientController extends Controller
{

    /**
     * 客户端授权登录
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function login(Request $request)
    {

        $user_id = $request->input('user_id', 0);
        $client_id = $request->input('client_id', '');

        if (empty($user_id)) {
            abort(400, '缺少用户参数');
        }

        if (empty($client_id)) {
            abort(400, '缺少客户端参数');
        }

        $mall_user = MallUser::find($user_id);
        if (!$mall_user) {
            abort(404, '用户信息没有找到');
        }

        if ($mall_user->userType == 1) {
            $mall_master = MallMaster::find($mall_user->mallID);
        } else {
            $mall_master = MallMaster::where('mallareaID', $mall_user->mallareaID)->first();
        }

        if (!$mall_master || $mall_master->useFlg == 0) {
            abort(404, '门店信息未找到');
        }

        Redis::setex('WDH_STEWARD_MALL_ID_' . session_id(), 8640000, $mall_master->mallID);
        Redis::setex('WDH_STEWARD_USER_ID_' . session_id(), 8640000, $mall_user->user_id);

        Redis::setex('WDH_CLIENT_ID_' . session_id(), 8640000, $client_id);
        Redis::setex('WDH_CLIENT_STEWARD_MALL_ID_' . $client_id, 8640000, $mall_master->mallID);
        Redis::setex('WDH_CLIENT_STEWARD_USER_ID_' . $client_id, 8640000, $mall_user->user_id);

        return redirect('/lar/steward');

    }


    /**
     * 订单打印详情获取
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function order_fetch(Request $request)
    {

        $client_id = $request->input('client_id', '');
        $order_id = $request->input('order_id', []);

        if (empty($client_id)) {
            return response()->json(['code'=>1000001, 'message'=>'客户端标识不能为空']);
        }

        $user_id = Redis::get('WDH_CLIENT_STEWARD_USER_ID_' . $client_id);
        $mall_id = Redis::get('WDH_CLIENT_STEWARD_MALL_ID_' . $client_id);

        if (!$user_id || !$mall_id) {
            return response()->json(['code'=>100002, 'message'=>'客户端登录已失效']);
        }

        $mall_data = MallMaster::find($mall_id);
        if (!$mall_data) {
            return response()->json(['code'=>100003, 'message'=>'门店信息没有找到']);
        }

        if (!empty($order_id)) {
            $bill_data  = Bill::where('mallID', $mall_id)
                                ->whereIn('bill_no', $order_id)
                                ->get();
        } else {
            $bill_data  = Bill::where('mallID', $mall_id)->get();
        }

        $website_name = ConfigureFunction::getConfigureField(43, 'website_name');
        $domain_url = ConfigureFunction::getConfigureField(43, 'domain_url');

        $return_data = [];
        $bill_type = [
            30 => '百度外卖订单',
            31 => '美团外卖订单',
            32 => '饿了么订单',
            33 => '京东到家订单'
        ];

        if ($bill_data->count() > 0) {

            foreach($bill_data as $bill) {

                $bill_goods = BillGoods::getGoods($bill->bill_no);
                $goods_data = [];

                foreach($bill_goods as $g) {
                    $goods_data[] = [
                        'sku_code' => app_to_string($g['product_code']),
                        'name' => app_to_string($g['goods_name']),
                        'number' => app_to_int($g['goods_amount']),
                        'price' => app_to_string($g['goods_purchasePrice'])
                    ];
                }

                $send_time = $bill->send_time;
                if (empty($send_time) && (!empty($bill->pickup_start_time) && $bill->pickup_start_time != '0000-00-00 00:00:00')) {
                    $send_time = date('m-d H:s', strtotime($bill->pickup_start_time));
                    if (!empty($bill->pickup_end_time) && $bill->pickup_end_time != '0000-00-00 00:00:00') {
                        $send_time .= ' ~ ' . date('m-d H:s', strtotime($bill->pickup_end_time));
                    }
                }

                $return_data[] = [
                    'title' => $website_name,
                    'order_id' => app_to_string($bill->bill_no),
                    'order_name' => isset($bill_type[$bill->billType]) ? $bill_type[$bill->billType] : '微电汇订单',
                    'order_type' => isset($bill_type[$bill->billType]) ? 2 : 1,
                    'shop_name' => app_to_string($mall_data->mallName),
                    'shop_tel' => app_to_string($mall_data->phone),
                    'shop_address' => app_to_string($mall_data->address),
                    'pay_name' => app_to_string($bill->payTypeName),
                    'total_fee' => app_to_string($bill->bill_payable),
                    'discount_fee' => app_to_string($bill->bill_subtract_money),
                    'deliver_fee' => app_to_string($bill->deliver_feePaid),
                    'package_fee' => app_to_string($bill->additional_expenses),
                    'create_time' => app_to_string(date('Y-m-d H:i')),
                    'send_name' => app_to_string($bill->sendTypeName),
                    'send_time' => app_to_string($send_time),
                    'deliver_name' => app_to_string($bill->deliver_name),
                    'deliver_mobile' => app_to_string($bill->deliver_mobile),
                    'deliver_address' => app_to_string($bill->deliver_address),
                    'code_url' => $domain_url,
                    'remark' => app_to_string($bill->remark),
                    'goods' => $goods_data
                ];

            }

        }

        return response()->json(['code'=>200, 'message'=>'ok', 'data'=>$return_data]);

    }

    /**
     * 待提醒消息获取
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function notice(Request $request)
    {

        $client_id = $request->input('client_id', '');

        if (empty($client_id)) {
            return response()->json(['code'=>1000001, 'message'=>'客户端标识不能为空']);
        }

        $user_id = Redis::get('WDH_CLIENT_STEWARD_USER_ID_' . $client_id);
        $mall_id = Redis::get('WDH_CLIENT_STEWARD_MALL_ID_' . $client_id);

        if (!$user_id || !$mall_id) {
            return response()->json(['code'=>100002, 'message'=>'客户端登录已失效']);
        }

        $return_data = [
            [
                'notice_type'=>1,
                'order_number'=>0,
                'order_list'=>[]
            ],
            [
                'notice_type'=>2,
                'order_number'=>0
            ],
            [
                'notice_type'=>3,
                'order_number'=>0
            ]
        ];

        //订单新订单数量计算和订单号获取
        $new_count = Bill::where(['mallID'=>$mall_id, 'bill_status'=>1, 'order_receive'=>0, 'hang_up'=>0])
                            ->where('split_type', '<>', 2)
                            ->where(function($query){
                                $query->where('pay_type', 1)
                                    ->orWhere(function($q){
                                        $q->where('pay_type', 2)
                                            ->where('pay_status', 1);
                                    });
                            })->get();

        if ($new_count->count() > 0) {
            $mall_master = MallMaster::find($mall_id); //是否设置自动打印
            if($mall_master->auto_print_pc){
                foreach($new_count as $order) {
                    $bill_print_log = BillPrintLog::where([
                                                        'bill_no' => $order->bill_no,
                                                        'device' => $client_id,
                                                        'device_site' => 1])
                                                    ->first();
                    if(!$bill_print_log){
                        $return_data[0]['order_list'][] = app_to_int($order->bill_no);
                    }
                }
            }
            $return_data[0]['order_number'] = app_to_int($new_count->count());
        }

        //订单催单数量计算
        $remind_count = Bill::join('takeout_bill', 'bill_master.bill_no', '=', 'takeout_bill.bill_no')
                                ->where(['mallID'=>$mall_id, 'hang_up'=>0, 'takeout_bill.remind'=>1])
                                ->where('split_type', '<>', 2)
                                ->where('bill_status', '<>', 5)
                                ->where(function($query){
                                    $query->where('pay_type', 1)
                                        ->orWhere(function($q){
                                            $q->where('pay_type', 2)
                                                ->where('pay_status', 1);
                                        });
                                })->count();
        $return_data[1]['order_number'] = app_to_int($remind_count);

        //订单退单数量计算
        $return_count = Bill::join('takeout_bill', 'bill_master.bill_no', '=', 'takeout_bill.bill_no')
                                ->where(['bill_master.mallID'=>$mall_id, 'bill_master.hang_up'=>0, 'bill_master.billType'=>21])
                                ->where('takeout_bill.apply_cancel', '>', 0)
                                ->where('bill_master.split_type', '<>', 2)
                                ->where(function($query){
                                    $query->where('pay_type', 1)
                                        ->orWhere(function($q){
                                            $q->where('pay_type', 2)
                                                ->where('pay_status', 1);
                                        });
                                })->count();
        $return_data[2]['order_number'] = app_to_int($return_count);

        return response()->json(['code'=>200, 'message'=>'ok', 'data'=>$return_data]);

    }

}
